import axios from 'axios'
const chalk = require('chalk')
import { Toast } from 'mint-ui';
import {tokenErr} from './js2androidTokenErr';

// create an axios instance
const service = axios.create({
  //baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  baseURL: window.localStorage.getItem('android_apihost'),
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    const token = window.localStorage.getItem('android_token');
    if (token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['X-Token'] = token
    }
    return config
  },
  error => {
    // do something with request error
    console.log(chalk.redBright(error))
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    console.log(response);
    const res = response.data

    // if the custom code is not 20000, it is judged as an error.
    if (res.code !== 0) {
      Toast({
        message: res.msg || 'Error',
        position: 'middle',
        duration: 5000
      });
      if(res.code == 201 || res.code == 202) {
        //要跟后台再确认一下，token过期，和有其他人登录是，通知android跳转到登录节目
        tokenErr();
      }
      return Promise.reject(res)
    } else {
      return res
    }
  },
  error => {
    console.log(error) // for debug
    Toast({
      message: error.message,
      position: 'middle',
      duration: 5000
    });
    return Promise.reject(error)
  }
)

export default service
